let express = require('express');
let router = express.Router();

// const fs = require('fs');
// const path = require('path');

let PictureService = require('../services/PictureService');

const UUID = require('node-uuid');
const OSS = require('ali-oss');

const MultipartMiddleware = require('connect-multiparty')();
const ValidStatus = require('../../config/midware/valid-status');
const ValidBelong = require('../../config/midware/valid-belong');

const file_types = ['image','css','js','html'];
const suf_types = {
    image: /.(gif|jpg|jpeg|png|GIF|JPG|JPEG|PNG)$/,
    css: /.css$/,
    js: /.js$/,
    html: /.html$/
}
const validator = {
    id: '请检查id',
    address: '请先上传文件',
    label: '请输入图片名称（标签）'
}

function validResParam(keyArr, item, done){
    let valid = true;
    for (let k of keyArr) {
        if(!item[k]){
            var msg = validator[k];
            valid = false;
            break;
        }
    }
    if(!valid) done.status(400).send({code: 400, msg});
    return valid;
}

router.get('/', (req, res, next) => {
    res.send({
        code: 200,
        data: null,
        msg: '图片接口请求成功'
    })
});
// 上传文件
router.post('/:file_type/upload', ValidStatus, MultipartMiddleware, (req, res, next) => {
    let {body, params, files} = req;
    let client_file_type = params.file_type;
    if(file_types.includes(client_file_type)) {
        // console.log(files);
        
        // [miao] 对应前端组件的 field 做唯一标识
        let file = files['miao'];
        
        // 随机文件名
        let _f_name = UUID.v1();
        // 文件后缀
        let _suf_name = /\.[^\.]+$/.exec(body.name);
        
        // 格式校验
        if(!suf_types[client_file_type].test(_suf_name)) {
            res.status(400).send({code: 400, msg: '文件格式不正确'})
            return;
        }

        /**
         * 上传本地文件夹
         */
        // var source = fs.createReadStream(file.path); //读取临时文件流
        // var output = path.join(__dirname,"../assets/"+client_file_type, _f_name + _suf_name); 
        // var dest = fs.createWriteStream(output);
        // source.pipe(dest);
        // source.on('end', function() {
        //     fs.unlinkSync(file.path);
        //     console.log('保存成功')
        // }); 
        // source.on('error', function(err) {
        //     console.log('文件复制出错',err)
        // });

        try {
            let Client = new OSS($config._aoc.conf);
            let uri = $config._aoc.path + client_file_type + '/' + _f_name + _suf_name;
            // ----- 临时处理方案，参数带有address或label则为编辑操作 ----- 
            if(body.address) uri = body.address.replace(new RegExp($config._aoc.domain,"g"), '');
            // ----- 临时处理方案，参数带有address或label则为编辑操作 ----- 
            
            Client.put(uri, file.path).then(result => {
                res.send({
                    code: 200,
                    data: $config._aoc.domain + result.name,
                    msg: '上传成功'
                })
            })
        } catch (e) {
            next(e);
        }
    }else{
        res.status(400).send({code: 400, msg: '请检查您的接口url'})
    }
});
// 文件列表
router.get('/:file_type/list', async ctx => {
    if(file_types.includes(ctx.params.file_type)) {
        let data = await PictureService.getPicList(Object.assign(ctx.params,ctx.query), ctx.next);
        ctx.res.send($utils._formmat_send_data({data}));
    }else{
        ctx.res.status(400).send({code: 400, msg: '请检查您的接口url'})
    }
});
// 添加文件
router.post('/:file_type/create', ValidStatus, async ctx => {
    console.log('=====', ctx.params);
    console.log('-----', ctx.body);
    
    
    if(file_types.includes(ctx.params.file_type)) {
        if(!validResParam(['address', 'label'], ctx.body, ctx.res)) return;
        let data = await PictureService.createPic(Object.assign(ctx.params,ctx.body));
        ctx.res.send($utils._formmat_send_data({data, changeCount: true}));
    }else{
        ctx.res.status(400).send({code: 400, msg: '请检查您的接口url'})
    }
});
// 查询文件
router.get('/find/:id', async ctx => {
    let data = await PictureService.findPic(ctx.params);
    ctx.res.send($utils._formmat_send_data({data}));
})
// 修改文件
router.post('/update', ValidStatus, ValidBelong, async ctx => {
    if(!validResParam(['id', 'address', 'label'], ctx.body, ctx.res)) return;
    let data = await PictureService.updatePic(ctx.body);
    ctx.res.send($utils._formmat_send_data({data, changeCount: true}));
})
// 删除文件
router.post('/delete/:id', ValidStatus, ValidBelong, async ctx => {
    let data = await PictureService.deletePic(ctx.params);
    ctx.res.send($utils._formmat_send_data({data, changeCount: true}));
})

module.exports = router;
